package com.rong.action;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.text.DateFormat;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.rong.DAO.ZynBusiInputDAO;
import com.rong.DAO.ZynSellDAO;
import com.rong.DAO.ZynTransferDAO;
import com.rong.ORM.ZynBusiInput;
import com.rong.ORM.ZynSell;
import com.rong.ORM.ZynTransfer;
import com.rong.ORM.ZynUser;
import com.rong.ORM.ZynUserRight;
import com.rong.action.ParaAction;
import com.rong.ORM.ZynQueryCriter;
import com.rong.DAO.ZynBusiInputVDAO;
import com.rong.ORM.ZynBusiInputV;


public class BusiAction extends ActionSupport {

	ZynBusiInput busi=new ZynBusiInput();
	ZynBusiInputDAO busiDao=new ZynBusiInputDAO();
	private List<ZynBusiInput> list;
	private String saveFlag="";
	private int id=-1; // the busi id indatabase.
	private List<ZynTransfer> transfList;
	private List<ZynSell> sellList;
	ZynTransferDAO traferDao=new ZynTransferDAO();
	ZynSellDAO sellDao=new ZynSellDAO();
	ParaAction paraAct=new ParaAction();
	
	private int rowsPerPage =25;// 每页显示几条
	private int page = 1; // 默认当前页
	private int totalPage;// 总共多少页
	private int planNum;// 总过多少条
	
	ZynQueryCriter queryCrt=new ZynQueryCriter();
	
	
	private String part="";
	int statusid=0;
	private String hxright="";
	private String returnto="s_edit_one";
	
	ZynBusiInputVDAO blistDao=new ZynBusiInputVDAO();
	private List<ZynBusiInputV> bvlist;
	/**
	 * @return the transfList
	 */
	public List<ZynTransfer> getTransfList() {
		return transfList;
	}
	/**
	 * @param transfList the transfList to set
	 */
	public void setTransfList(List<ZynTransfer> transfList) {
		this.transfList = transfList;
	}
	/**
	 * @return the sellList
	 */
	public List<ZynSell> getSellList() {
		return sellList;
	}
	/**
	 * @param sellList the sellList to set
	 */
	public void setSellList(List<ZynSell> sellList) {
		this.sellList = sellList;
	}
	/**
	 * @return the busi
	 */
	public ZynBusiInput getBusi() {
		return busi;
	}
	/**
	 * @param busi the busi to set
	 */
	public void setBusi(ZynBusiInput busi) {
		this.busi = busi;
	}
	/**
	 * @return the list
	 */
	public List<ZynBusiInput> getList() {
		return list;
	}
	/**
	 * @param list the list to set
	 */
	public void setList(List<ZynBusiInput> list) {
		this.list = list;
	}
	/**
	 * @return the saveFlag
	 */
	public String getSaveFlag() {
		return saveFlag;
	}
	/**
	 * @param saveFlag the saveFlag to set
	 */
	public void setSaveFlag(String saveFlag) {
		this.saveFlag = saveFlag;
	}
	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}
	
	
	
	/**
	 * @return the rowsPerPage
	 */
	public int getRowsPerPage() {
		return rowsPerPage;
	}
	/**
	 * @param rowsPerPage the rowsPerPage to set
	 */
	public void setRowsPerPage(int rowsPerPage) {
		this.rowsPerPage = rowsPerPage;
	}
	/**
	 * @return the page
	 */
	public int getPage() {
		return page;
	}
	/**
	 * @param page the page to set
	 */
	public void setPage(int page) {
		this.page = page;
	}
	/**
	 * @return the totalPage
	 */
	public int getTotalPage() {
		return totalPage;
	}
	/**
	 * @param totalPage the totalPage to set
	 */
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
	/**
	 * @return the queryCrt
	 */
	public ZynQueryCriter getQueryCrt() {
		return queryCrt;
	}
	/**
	 * @param queryCrt the queryCrt to set
	 */
	public void setQueryCrt(ZynQueryCriter queryCrt) {
		this.queryCrt = queryCrt;
	}
	
	
	
	
	/**
	 * @return the part
	 */
	public String getPart() {
		return part;
	}
	/**
	 * @param part the part to set
	 */
	public void setPart(String part) {
		this.part = part;
	}
	/**
	 * @return the statusid
	 */
	public int getStatusid() {
		return statusid;
	}
	/**
	 * @param statusid the statusid to set
	 */
	public void setStatusid(int statusid) {
		this.statusid = statusid;
	}
	/**
	 * @return the hxright
	 */
	public String getHxright() {
		return hxright;
	}
	/**
	 * @param hxright the hxright to set
	 */
	public void setHxright(String hxright) {
		this.hxright = hxright;
	}
	/**
	 * @return the planNum
	 */
	public int getPlanNum() {
		return planNum;
	}
	/**
	 * @param planNum the planNum to set
	 */
	public void setPlanNum(int planNum) {
		this.planNum = planNum;
	}
	
	
	/**
	 * @return the returnto
	 */
	public String getReturnto() {
		return returnto;
	}
	/**
	 * @param returnto the returnto to set
	 */
	public void setReturnto(String returnto) {
		this.returnto = returnto;
	}
	
	/**
	 * @return the bvlist
	 */
	public List<ZynBusiInputV> getBvlist() {
		return bvlist;
	}
	/**
	 * @param bvlist the bvlist to set
	 */
	public void setBvlist(List<ZynBusiInputV> bvlist) {
		this.bvlist = bvlist;
	}
	@Override
    public String execute() throws Exception {
		
		  ActionContext actionContext = ActionContext.getContext();         
		     Map session = actionContext.getSession(); 
		     ZynUser loginUser=(ZynUser)session.get("loginUser");   //登录用户		 
		boolean insertTf=true;     
		this.setSaveFlag("");
        DateFormat format2=new java.text.SimpleDateFormat("yyyyMMdd");
        int s=busiDao.findByHeatDate(this.busi.getHeatDate()).size()+1;
        
        
        String seq = String.format("%05d", s);  
        
        String n=format2.format(this.busi.getHeatDate())+seq;
        this.busi.setNum(n);
        this.busi.setExtattrint1(10);  //采热的状态，初始为录入
        this.busi.setExtattrint2(10);  //采水的状态，初始为录入
        
        

        int paraid=paraAct.findbydate(this.busi.getHeatDate()); //取当时的油价id
        if(paraid==-1){
        	System.out.println("[BusiAction]=====warning========单据日期："+this.busi.getHeatDate()+"内没有可用的系统参数(油价..)==============");
        }else{
        	this.busi.setExtattrint3(paraid);
        }
        
        this.busi.setExtattrint4(loginUser.getComId());  //单据所属分公司(zyn_company.id)
        
		busiDao.save(this.busi);        //保存注册的busi对象
		//保存运费和销售费用LIST
		if(this.getBusi().getExtAttr7().equalsIgnoreCase("true")&&transfList!=null &&!transfList.equals("")){
			for(Iterator<ZynTransfer> iterTra=transfList.iterator();iterTra.hasNext();){
				ZynTransfer trfer=(ZynTransfer)iterTra.next();
				if(trfer==null||(trfer.getComFromId()==-1&&trfer.getComToId()==-1)){insertTf =false ;continue;}// if transfer num is null ,this is no record ,do not save this record,
				trfer.setExtattr2(this.busi.getId());// the total busi id	
				trfer.setExtattr3(10);//录入状态
				trfer.setExtattr4(loginUser.getComId());//单据所属分公司(zyn_company.id)
				trfer.setExtattrdate2(this.busi.getHeatDate());//运输单据日期
				traferDao.save(trfer);
			}			
		}
		
		
		
		if(sellList!=null && !sellList.equals("")){
			for(Iterator<ZynSell> iterSell=sellList.iterator();iterSell.hasNext();){
				ZynSell sell=(ZynSell)iterSell.next();
				if(sell==null||sell.getSellNum().length()==0){continue;} // the same with upper 
				sell.setExtattr2(this.busi.getId());  // the total busi id
				sell.setOfferHeatTime(new java.sql.Timestamp(this.busi.getHeatDate().getTime()));  // the offerHeatDate is the heat part heatDate
				sell.setExtattr3(10) ;//录入状态
				sell.setExtattr4(loginUser.getComId());//单据所属分公司(zyn_company.id)
				sellDao.save(sell);	
				
				//如果运输单据部分即承包方结算 没选，没有录入运输单据，则插入相应的运输记录，以便和供热单据对应，结算报表和绩效好出数据
				if(this.getBusi().getExtAttr7().equalsIgnoreCase("false")||!insertTf){
						ZynTransfer trfertemp=new ZynTransfer();
						trfertemp.setComFromId(sell.getComFromId());
						trfertemp.setComToId(sell.getComToId());
						trfertemp.setCarId(sell.getCarId());
						trfertemp.setTranNum(sell.getSellNum());
						trfertemp.setStmtStyle(sell.getStmtStyle());
						trfertemp.setPrice(0.0);
						trfertemp.setAmount(0.0);
						trfertemp.setSum(0.0);
						
						trfertemp.setExtattr2(this.busi.getId());
						trfertemp.setExtattr3(90);      //因为是系统默认的且总额为0，则状态为90，已签批
						trfertemp.setExtattr4(loginUser.getComId());//单据所属分公司(zyn_company.id)
						trfertemp.setExtattrdate2(this.busi.getHeatDate());//运输单据日期
						traferDao.save(trfertemp);
				}
				//end
				
				
			}			
		}
		
		
		
		//保存运费和销售费用LIST end
		 this.setSaveFlag("保存成功..");
        return "success";
    }
	 public String findall() throws Exception {
	    
		 this.setList(busiDao.findAll());        //保存注册的user对象
		
	        return "success_list";
	    }

	 public String findbyid() throws Exception {
	        System.out.println("===================statuscode ="+this.getStatusid());
		this.setBusi(busiDao.findById(this.getId()));// find the busi by id	 
		//System.out.println("=================利用get，使load执行数据库查询============="+this.busi.getNum());
		this.setSellList(sellDao.findByExtattr2(this.getId()));   //根据业务总ID得到销售列表
		this.setTransfList(traferDao.findByExtattr2(this.getId()));   //根据业务总ID得到运输列表 	 
	        return "s_find_one";
	       
	    }
	 public String edit() throws Exception {
		 Integer temptrasferid=-2;
		 int flag=0;
		 this.setSaveFlag("");
			 busiDao.merge(this.getBusi());// edit the busi by id			
			//保存运费和销售费用LIST
			if(transfList!=null &&!transfList.equals("")){
				for(Iterator<ZynTransfer> iterTra=transfList.iterator();iterTra.hasNext();){
					ZynTransfer trfer=(ZynTransfer)iterTra.next();
					if(trfer.getId()==temptrasferid){ //新增的一条记录，则插入
						trfer.setId(null);
						flag=1;
					}
					
					if(trfer.getTranNum().equalsIgnoreCase("")){ //为空，标识删除该条记录
						traferDao.delete(trfer);
					}else{
					traferDao.merge(trfer);   //否则更新该记录，update or insert
					}
					
					if(flag!=1){
					temptrasferid=trfer.getId();
					}
				}			
			}
			
		 temptrasferid=-2;
		 flag=0;
			if(sellList!=null && !sellList.equals("")){
				for(Iterator<ZynSell> iterSell=sellList.iterator();iterSell.hasNext();){
					ZynSell sell=(ZynSell)iterSell.next();
					sell.setOfferHeatTime(new java.sql.Timestamp(this.busi.getHeatDate().getTime()));  // the offerHeatDate is the heat part heatDate
					
					if(sell.getId()==temptrasferid){ //新增的一条记录，则插入
						sell.setId(null);
						flag=1;
					}
					if(sell.getSellNum().equalsIgnoreCase("")){
						sellDao.delete(sell);
					}else{
						sellDao.merge(sell);	
					}
					if(flag!=1){
						temptrasferid=sell.getId();
						}
					
				}			
			}
			
			//保存运费和销售费用LIST end
			 this.setSaveFlag("保存成功..");
			 // return "s_edit_one";
			 return this.returnto;
		    }
	 public String delete() throws Exception {
	        
			busiDao.delete(busiDao.findById(this.getId()));// delete the busi by id			
		    return "s_delete_one";
		    }
	
	 
	 /***
	  * 采热查询结果列表
	  * **/
	 public String  queryBillList() throws Exception {		    
		 		
	      this.setList(busiDao.queryBillListByPage(page, rowsPerPage,this.getQueryCrt()));
	     
	     this.setPlanNum(busiDao.queryBillListtatolRows(this.getQueryCrt()).size());
	     this.setTotalPage(this.getPlanNum() % this.getRowsPerPage()==0?this.getPlanNum()/this.getRowsPerPage():this.getPlanNum()/this.getRowsPerPage()+1);

	        return "success_list";
	    }
	 /*** 
	  * 采热查询结果列表，连接了运输和供热表
	  * **/
	 public String findallblist() throws Exception {
	 		
	      this.setBvlist(blistDao.queryBillListByPage(page, rowsPerPage,this.getQueryCrt()));
	     
	     this.setPlanNum(blistDao.queryBillListtatolRows(this.getQueryCrt()).size());
	     this.setTotalPage(this.getPlanNum() % this.getRowsPerPage()==0?this.getPlanNum()/this.getRowsPerPage():this.getPlanNum()/this.getRowsPerPage()+1);

	        return "success_list";
	 }
	 
	 
	 
	 
}
